/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MenuCadastrarEditarServicoPesca.java
 *
 * Created on 21/09/2009, 10:25:58
 */
package JPaneis;

import Conector.Conector;
import Data.ServicoPesca;
import java.awt.Component;
import java.awt.GridLayout;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import siii.MenuPadrao;


public class MenuCadastrarEditarServicoPesca_1 extends javax.swing.JPanel {

    private MenuPadrao menuPadrao;
    private Conector conector;
    private String objetivo;
    private List<Map<String, ?>> lista;
    private static final String numServ = "NUMERO_SERVICO";
    private ImageIcon iconeOK;
    private ImageIcon iconeERRO;
    private ImageIcon iconeATENCAO;

    /** Creates new form MenuCadastrarEditarServicoPesca */
    public MenuCadastrarEditarServicoPesca_1(MenuPadrao m, Conector con) {
        this.menuPadrao = m;
        this.conector = con;
        this.objetivo = "C";
        initComponents();
        jButtonRemover.setVisible(false);
        refreshList();
        iconeOK = new ImageIcon(getClass().getResource("/Images/fish-48x48ok.png"));
        iconeERRO = new ImageIcon(getClass().getResource("/Images/fish-48x48erro.png"));
        iconeATENCAO = new ImageIcon(getClass().getResource("/Images/fish-48x48atencao1.png"));
    }

    public MenuCadastrarEditarServicoPesca_1(MenuPadrao m, String a, Conector con) {
        this.menuPadrao = m;
        this.conector = con;
        this.objetivo = "E";
        initComponents();
        refreshList();
        iconeOK = new ImageIcon(getClass().getResource("/Images/fish-48x48ok.png"));
        iconeERRO = new ImageIcon(getClass().getResource("/Images/fish-48x48erro.png"));
        iconeATENCAO = new ImageIcon(getClass().getResource("/Images/fish-48x48atencao1.png"));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelCadastrarServicoPesca = new javax.swing.JLabel();
        jButtonCancelar = new javax.swing.JButton();
        jButtonInserir = new javax.swing.JButton();
        jButtonRemover = new javax.swing.JButton();
        servPescTurno = new javax.swing.JComboBox();
        jLabelTurno = new javax.swing.JLabel();
        servPescPeriodo = new javax.swing.JComboBox();
        jLabelPeríodo = new javax.swing.JLabel();
        jScrollPaneServPesc = new javax.swing.JScrollPane();
        jListServPesc = new javax.swing.JList();
        jLabelTipo = new javax.swing.JLabel();
        servPescTipo = new javax.swing.JComboBox();
        valorServPesc = new javax.swing.JFormattedTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabelTipo1 = new javax.swing.JLabel();

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });

        jLabelCadastrarServicoPesca.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabelCadastrarServicoPesca.setText("Cadastrar Serviço Pesca");

        jButtonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/salvar.png"))); // NOI18N
        jButtonCancelar.setText("Ok");
        jButtonCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mouseClickedCancelarHandler(evt);
            }
        });

        jButtonInserir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/peixe_add.png"))); // NOI18N
        jButtonInserir.setText("Inserir");
        jButtonInserir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInserirActionPerformed(evt);
            }
        });

        jButtonRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/peixe_cancelar2.png"))); // NOI18N
        jButtonRemover.setText("Remover");
        jButtonRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoverActionPerformed(evt);
            }
        });

        servPescTurno.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Diurno", "Noturno" }));
        servPescTurno.setName("Turno"); // NOI18N

        jLabelTurno.setText("Turno");

        servPescPeriodo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Integral", "Meio-período" }));
        servPescPeriodo.setName("Periodo"); // NOI18N

        jLabelPeríodo.setText("Período");

        jListServPesc.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListServPesc.setName("Lista de Cadastro de Setviço de Pesca"); // NOI18N
        jListServPesc.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListServPescMouseClicked(evt);
            }
        });
        jListServPesc.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListServPescValueChanged(evt);
            }
        });
        jScrollPaneServPesc.setViewportView(jListServPesc);

        jLabelTipo.setText("Tipo");

        servPescTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Homem", "Mulher", "Criança" }));
        servPescTipo.setName("Turno"); // NOI18N

        valorServPesc.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.##"))));

        jLabel13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/servico_pesca.png"))); // NOI18N

        jLabelTipo1.setText("Valor");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(68, 68, 68)
                        .addComponent(jScrollPaneServPesc, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabelTurno)
                                    .addComponent(jLabelPeríodo)
                                    .addComponent(jLabelTipo)
                                    .addComponent(jLabelTipo1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(servPescTurno, 0, 176, Short.MAX_VALUE)
                                            .addComponent(servPescPeriodo, 0, 176, Short.MAX_VALUE)))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(servPescTipo, 0, 176, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(9, 9, 9)
                                        .addComponent(valorServPesc, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE))))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addComponent(jButtonRemover)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jButtonInserir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jButtonCancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))))
                        .addGap(231, 231, 231))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelCadastrarServicoPesca, javax.swing.GroupLayout.PREFERRED_SIZE, 562, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jLabelCadastrarServicoPesca, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(40, 40, 40)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabelTurno)
                                    .addComponent(servPescTurno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabelPeríodo)
                                    .addComponent(servPescPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabelTipo)
                                    .addComponent(servPescTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabelTipo1)
                                    .addComponent(valorServPesc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButtonInserir)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jButtonRemover)
                                    .addComponent(jButtonCancelar)))
                            .addComponent(jScrollPaneServPesc, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel13)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void mouseClickedCancelarHandler(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mouseClickedCancelarHandler
        // TODO add your handling code here:
        menuPadrao.trocaPanel2(menuPadrao.getMenuPrincipal());
    }//GEN-LAST:event_mouseClickedCancelarHandler

    private void jButtonInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInserirActionPerformed
        try {


            if (this.objetivo.equals("C")) {
                ServicoPesca servPesca = this.readScreen();
                if (servPesca != null) {
                    if (!conector.consultarServicoPescaCadastrado(servPesca)) {
                        System.out.println("CADASTRANDO SERVICO");
                        if (conector.cadastrarServicoPesca(servPesca)) {
                            JOptionPane.showMessageDialog(this, "Serviço de pesca cadastrado", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeOK);
                        } else {
                            JOptionPane.showMessageDialog(this, "Serviço de pesca não cadastrado", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeERRO);
                        }

                    } else {
                        JOptionPane.showMessageDialog(this, "Serviço de pesca previamente cadastrado", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeERRO);
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "Favor preencher Valor", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeATENCAO);
                }
            } else if (this.objetivo.equals("E")) {

                ServicoPesca servPesca = this.readScreen();
                Map<String, ?> itens = lista.get(jListServPesc.getSelectedIndex());
                Integer numeroServico = (Integer) itens.get(numServ);
                System.out.println("ESTOU FAZENDO UPDATE DESTE SERVICO: " + servPesca + " COM O NUMERO " + numeroServico );

            }


        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // Atualiza a lista
        refreshList();

    }//GEN-LAST:event_jButtonInserirActionPerformed

    private void jButtonRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoverActionPerformed
        if (lista.size() >= 0){
            //pega da lista numero do servico.
            Integer num = (Integer) lista.get(jListServPesc.getSelectedIndex()).get(numServ);
            // remove do bd
            conector.removerServicoPesca(num);
        }
        // atualiza a 
        refreshList();
    }//GEN-LAST:event_jButtonRemoverActionPerformed

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        refreshList();
    }//GEN-LAST:event_formMouseClicked

    private void jListServPescMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListServPescMouseClicked
        if (lista.size() >= 0){
            //pega da lista numero do servico.
            Map<String, ?> itens = lista.get(jListServPesc.getSelectedIndex());
            // remove do bd

            setSelectedItem((String)itens.get("TURNO"), servPescTurno);
            setSelectedItem((String)itens.get("PERIODO"), servPescPeriodo);
            setSelectedItem((String)itens.get("TIPO"), servPescTipo);
            valorServPesc.setValue(itens.get("VALOR"));
            jButtonInserir.setText("Atualizar");
        }

    }//GEN-LAST:event_jListServPescMouseClicked

    public void setSelectedItem(String item, javax.swing.JComboBox combo) {

        if (combo.getItemCount() > 0) {
            for (int i = 0 ; i < combo.getItemCount(); i++){
                if(combo.getItemAt(i).equals(item.trim())){
                   // System.out.println("SELECIONOU " + i + ":" + item);
                    combo.setSelectedIndex(i);
                    break;
                }

            }
        }
    }

    private void jListServPescValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListServPescValueChanged




    }//GEN-LAST:event_jListServPescValueChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JButton jButtonInserir;
    private javax.swing.JButton jButtonRemover;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabelCadastrarServicoPesca;
    private javax.swing.JLabel jLabelPeríodo;
    private javax.swing.JLabel jLabelTipo;
    private javax.swing.JLabel jLabelTipo1;
    private javax.swing.JLabel jLabelTurno;
    private javax.swing.JList jListServPesc;
    private javax.swing.JScrollPane jScrollPaneServPesc;
    private javax.swing.JComboBox servPescPeriodo;
    private javax.swing.JComboBox servPescTipo;
    private javax.swing.JComboBox servPescTurno;
    private javax.swing.JFormattedTextField valorServPesc;
    // End of variables declaration//GEN-END:variables

    void refreshList() {
        try {
            this.lista = (List<Map<String,?>>) conector.doRawSql("SELECT * FROM SERVICOS_DISPONIVEIS_PESCA");
        } catch (Exception ex) {
            //Logger.getLogger(MenuCadastrarEditarServicoPesca.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }

         // String[][] dados = getListData();
          String[][] dados = getListData();
          //set list for JList
          if (dados != null){
            jListServPesc.setListData(dados);
            //create Renderer and dislpay
            System.out.println("colunas: " + dados[0].length);
            jListServPesc.setCellRenderer(new MyCellRenderer(dados[0].length));
          } else {
              jListServPesc.setListData(new String[]{});
          }
    }

    private String[][] getListData(){
        String[][] dados = null;
//        String campos = "TURNO, PERIODO, TIPO, VALOR";
        //List<Map<String,?>> lista = null;
        System.out.flush();
        int line = 0;
        int col = 0 ;


        for(Map<String,?> m : lista){
            if (dados == null){
                dados = new String[lista.size()][m.size()];
            }
            System.out.println(m);

            for(String key : m.keySet()){
                if (key.equals(numServ))
                    continue;
                System.out.println(key + ":" + m.get(key) + ":" + line + ":" + col);
                dados[line][col++] = m.get(key).toString();
            }
            line++;
            col=0;
        }

        return dados;
    }



    static class MyCellRenderer extends JPanel implements ListCellRenderer {

        ArrayList<JLabel> labels = new ArrayList();
        JLabel left, middle, right;
        int cols;

        MyCellRenderer(int cols) {
            this.cols = cols;
            setLayout(new GridLayout(1, cols));
            for (int i=0; i < cols;i++){
                JLabel label = new JLabel();
                label.setOpaque(true);
                add(label);
                labels.add(label);
            }
        }

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            int i = 0;
            for (JLabel jl : labels) {
                jl.setText(((String[])value)[i++]) ;
                if (isSelected) {
                    jl.setBackground(list.getSelectionBackground());
                    jl.setForeground(list.getSelectionForeground());
                } else {
                    jl.setBackground(list.getBackground());
                    jl.setForeground(list.getForeground());
                }
            }

            setEnabled(list.isEnabled());
            setFont(list.getFont());
            return this;
        }
    }

    private ServicoPesca readScreen() throws ParseException {

    String turno, periodo, tipo;
    float valor;
         turno = servPescTurno.getSelectedItem().toString();
         periodo = servPescPeriodo.getSelectedItem().toString();
         tipo = servPescTipo.getSelectedItem().toString();
         if(!valorServPesc.getText().replace("R","").replace("$", "").replace(",", ".").equals(""))
            valor = Float.parseFloat(valorServPesc.getText().replace("R","").replace("$", "").replace(",", "."));
         else
             return null;


         ServicoPesca serv_pesca = new ServicoPesca(turno, periodo, tipo, valor);
        return serv_pesca;
    }


}
